package com.dragon.logical.service.customer.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dragon.common.model.ResultCode;
import com.dragon.common.model.exception.CustomException;
import com.dragon.logical.service.avttendance.IScheduleService;
import com.dragon.logical.service.contract.ICommentService;
import com.dragon.logical.service.customer.FollowService;
import com.dragon.repository.config.annotation.DataScope;
import com.dragon.repository.entity.*;
import com.dragon.repository.mapper.CommentMapper;
import com.dragon.repository.mapper.FollowMapper;
import com.dragon.repository.mapper.OtherFileMapper;
import com.dragon.repository.mapper.ScheduleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * dragon 服务实现类
 * </p>
 *
 * @author sy
 * @since 2023-06-20
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements FollowService {

    @Autowired
    FollowMapper followMapper;
    @Autowired
    ICommentService commentService;
    @Autowired
    IScheduleService scheduleService;
    @Autowired
    ScheduleMapper scheduleMapper;
    @Autowired
    OtherFileMapper otherFileMapper;

    @Override
    @DataScope(adminAlias = "M", adminField = "admin_id",deptAlias = "M",deptField = "department_id")
    public Page<Follow> followList(String search, Integer adminId, Integer customerId, Integer page, Integer limit) {
        Page<Follow> followPage = new Page<>(page, limit);
        QueryWrapper<Follow> wrapper = new QueryWrapper<>();
        wrapper.like(StrUtil.isNotBlank(search), "M.follow_name", search)
                .eq(customerId != null, "M.customer_id", customerId)
                .eq(adminId != null, "M.admin_id", adminId)
                .orderByDesc("M.create_time");
        return followMapper.selectFollowPage(followPage, wrapper);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void addFollow(Follow follow){
        Follow fol = followMapper.selectById(follow.getId());
        if (fol != null){
            throw new CustomException(ResultCode.DATA_ALREADY_EXISTS);
        }
        follow.setStatus(0);
        follow.setCreateTime(DateUtil.date());
        followMapper.insert(follow);

        //添加附件
        List<OtherFile> otherFileList = follow.getOtherFileList();
        if (otherFileList != null || otherFileList.size() != 0){
            otherFileList.forEach(otherFile -> {
                otherFile.setStreamType(7);
                otherFile.setCorrelationId(follow.getId());
                otherFile.setCreateTime(DateUtil.date());
                otherFileMapper.insert(otherFile);
            });
        }

        //添加进日程
        Schedule schedule = new Schedule();
        schedule.setOwnerAdminIds(String.valueOf(follow.getAdminId()));
        schedule.setCreateTime(follow.getCreateTime());
        schedule.setStartTime(DateUtil.date());
        schedule.setCreateAdminId(follow.getAdminId());
        schedule.setTitle(follow.getFollowName());
        schedule.setContent(follow.getContent());
        schedule.setEndTime(follow.getNextTime());
        schedule.setEventType(0);
        scheduleService.addSchedule(schedule);

    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void updateFollow(Follow follow) {
        Follow follow1 = followMapper.selectById(follow.getId());
        if (follow1 == null){
            throw new CustomException(ResultCode.DATA_NOT_FOUND);
        }
        follow.setUpdateTime(DateUtil.date());
        //修改日程
        Schedule schedule = scheduleMapper.selectOne(new QueryWrapper<Schedule>()
                .lambda().eq(Schedule::getContent, follow.getContent())
                .eq(Schedule::getCreateTime, follow.getCreateTime()));
        schedule.setContent(follow.getContent());
        schedule.setTitle(follow.getFollowName());
        schedule.setEndTime(follow.getNextTime());
        scheduleMapper.updateById(schedule);
        //修改跟进记录
        followMapper.updateById(follow);
        //修改附件
        QueryWrapper<OtherFile> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(OtherFile::getStreamType,7)
                        .eq(OtherFile::getCorrelationId, follow.getId());
        if (follow.getOtherFileList() != null || follow.getOtherFileList().size() != 0){
            otherFileMapper.delete(wrapper);
            follow.getOtherFileList().forEach(otherFile -> {
                otherFile.setStreamType(7);
                otherFile.setCorrelationId(follow.getId());
                otherFile.setCreateTime(DateUtil.date());
                otherFileMapper.insert(otherFile);
            });
        }

    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void deleteFollow(Integer id){
        Follow follow = followMapper.selectById(id);
        //删除日程
        scheduleMapper.delete(new QueryWrapper<Schedule>()
                .lambda().eq(Schedule::getContent, follow.getContent())
                .eq(Schedule::getCreateTime, follow.getCreateTime()));
        //删除附件
        QueryWrapper<OtherFile> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(OtherFile::getStreamType,follow.getId())
                .eq(OtherFile::getCorrelationId, id);
        otherFileMapper.delete(wrapper);
        //删除跟进记录
        followMapper.deleteById(id);
    }


    @Override
    public List<Follow> viewByCustomerId(Integer customerId) {
        return followMapper.selectList(new QueryWrapper<Follow>().lambda().eq(Follow::getCustomerId,customerId));
    }

    @Override
    public Follow listById(Integer id) {
        Follow follow = followMapper.listById(id);
        //评论查询
        List<Comment> comments = commentService.listComment(id,7);
        follow.setCommentList(comments);
        //附件
        QueryWrapper<OtherFile> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(OtherFile::getStreamType,7)
                .eq(OtherFile::getCorrelationId, follow.getId());
        List<OtherFile> otherFileList = otherFileMapper.selectList(wrapper);
        follow.setOtherFileList(otherFileList);
        return follow;
    }

    @Override
    @DataScope(deptAlias = "M", deptField = "department_id")
    public Page<Follow> submitList(Integer page, Integer limit, Integer adminId){
        Page<Follow> followPage = new Page<>(page, limit);
        QueryWrapper<Follow> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(adminId != null, Follow::getAdminId,adminId)
                .orderByDesc(Follow::getCreateTime);
        return followMapper.selectFollowPage(followPage, wrapper);
    }

    @Override
    @DataScope(deptAlias = "M", deptField = "department_id")
    public Page<Follow> receptionList(Integer page, Integer limit, Integer adminId, Integer search){
        Page<Follow> followPage = new Page<>(page, limit);
        QueryWrapper<Follow> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .ne(adminId != null, Follow::getAdminId,adminId)
                .eq(search != null, Follow::getAdminId, search)
                .orderByDesc(Follow::getCreateTime);
        return followMapper.selectFollowPage(followPage, wrapper);
    }
}
